﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using Newtonsoft.Json.Linq;



namespace BEX.Core.Exchange.BTCE
{
    public class BTCE : Exchange
    {
        public BTCE()
            : base(ExchangeType.BTCE)
        {
            
        }
  

        internal override Tick GetCurrentTick(CurrencyPair pair)
        {

            // USD EUR RUB LTC
  
            BTCEResponse response = GetBTCETick(pair);

            Tick res = new Tick();

            

            res.Ask = Convert.ToInt32(response.ticker.buy * global.ConversionFactor);
            res.Bid = Convert.ToInt32(response.ticker.sell * global.ConversionFactor);
            res.Currency = pair;
            res.ExchangeSource = ExchangeType.BTCE;
            res.Time = DateTime.UtcNow;
            res.Spot = Convert.ToInt32(response.ticker.last * global.ConversionFactor);

            return res;
        }

        private BTCEResponse GetBTCETick(CurrencyPair pair)
        {
            var queryStr = string.Format(TickerURL, FormatCurrencyPairString(pair));

            var resp = Query(queryStr);

            return new BTCEResponse(JObject.Parse(resp) as JObject);
        }

        private static string Query(string url)
        {
            var request = WebRequest.Create(url);
            request.Proxy = WebRequest.DefaultWebProxy;
            request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            if (request == null)
            {
                throw new Exception("Non HTTP WebRequest");
            }
            return new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
        }

        protected override string _baseUrl
        {
            get { return ExchangeConfig.Default.BtceAPI_BaseURL; }
        }

        protected override string _tickPath
        {
            get { return ExchangeConfig.Default.BtceAPI_GetTickPath; }
        }

        protected override string _pairs
        {
            get { return ExchangeConfig.Default.Btce_Pairs; }
        }

        protected string FormatCurrencyPairString(CurrencyPair pair)
        {
            return String.Format(pair.Base.ToString().ToLower() + "_" + pair.Counter.ToString().ToLower());
        }
    }

}
